package com.gitee.ywj1352.ds;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @author wenjie.yang on 2019/9/10.
 */
public class ThreadDemo {

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Semaphore semaphore = new Semaphore(2);
        Myrun myrun = new Myrun(semaphore);
        for (int i = 0; i < 10; i++) {
            executorService.submit(myrun);
        }
        Thread.sleep(2000);
        for (int i = 0; i < 10; i++) {
            executorService.submit(myrun);
        }

    }

    private static class Myrun implements Runnable {

        private Semaphore semaphore;
        private Integer i = 1;

        public Myrun(Semaphore semaphore) {
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                if (semaphore.tryAcquire()) {
                    System.out.println("得到信号:" + Thread.currentThread().getName());
                    Thread.sleep(1000);
                    semaphore.release();
                    System.out.println("释放信号量:"+ Thread.currentThread().getName());
                } else {
                    System.out.println("超过信号量:" + Thread.currentThread().getName());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}
